package com.yumao.recyclerview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

/**
 * Created by Administrator on 2017/3/1.
 */

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    private LayoutInflater inflater;
    private List<String> list;
    private RecyclerClickListener listener;

    public MyAdapter(Context context, List<String> list) {
        this.list = list;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.recycler_item, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        holder.textView.setText(list.get(position));
        if (listener != null) {
            holder.textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onClick(v, holder.getLayoutPosition());
                }
            });
            holder.textView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    listener.onLongClick(v, holder.getLayoutPosition());
                    return true;
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public void add() {
        list.add(1, "inset one");
        notifyItemInserted(1);
    }

    public void delete() {
        list.remove(1);
        notifyItemRemoved(1);
    }

    public void setRecyclerClickListener(RecyclerClickListener listener) {
        this.listener = listener;
    }

    public interface RecyclerClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, int position);
    }
}

class MyViewHolder extends RecyclerView.ViewHolder {
    TextView textView;

    MyViewHolder(View itemView) {
        super(itemView);
        textView = (TextView) itemView;
    }
}
